package com.xcw.jac;

import java.security.*;
import java.util.Base64;

public class KeyPairGeneratorExample {
    public static void main(String[] args) throws Exception {
        // 使用RSA算法生成KeyPair对象
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048); // 指定密钥长度
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // 获取私钥
        PrivateKey privateKey = keyPair.getPrivate();
        System.out.println(privateKey.getEncoded());
        byte[] privateKeyBytes = privateKey.getEncoded();

        // 获取公钥
        PublicKey publicKey = keyPair.getPublic();
        byte[] publicKeyBytes = publicKey.getEncoded();

        // 将私钥和公钥转换为Base64字符串
        String privateKeyBase64 = Base64.getEncoder().encodeToString(privateKeyBytes);
        String publicKeyBase64 = Base64.getEncoder().encodeToString(publicKeyBytes);

        // 打印私钥和公钥
        System.out.println("Private Key: " + privateKeyBase64);
        System.out.println("Public Key: " + publicKeyBase64);
    }
}